<template>
  <basic-container>
    <el-row>
      <el-col :span="13">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          :page.sync="page"
          :permission="permissionList"
          :before-open="beforeOpen"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @row-click="rowClick"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
          :before-close="beforeClose"
        >
          <!-- <div class="informationLabel el-tabs el-tabs--top el-tabs--border-card"></div> -->
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productpackingconfig_delete" @click="handleDelete">删 除 </el-button>
          </template>
          <template slot-scope="{ row }" slot="isOnlinePrint">
            <el-tag :class="row.isOnlinePrint ? 'successTag' : 'dangerTag'">{{ row.isOnlinePrint === false ? '否' : '是' }}</el-tag>
          </template>
        </avue-crud>
      </el-col>
      <el-col :span="11">
        <el-tabs type="border-card" style="margin: 10px" v-if="isShowDetailTable">
          <el-tab-pane label="成品包装配置详情">
            <avue-crud
              :option="detailOption"
              :table-loading="detailLoading"
              :data="detailData"
              :permission="permissionList"
              ref="detailCrud"
              @selection-change="selectionDetailChange"
              @refresh-change="detailRefreshChange"
              @tree-load="treeLoad"
            >
              <template slot="menuLeft">
                <el-button v-if="permission.productpackingconfig_add && this.packingConfigId" type="primary" size="small" icon="el-icon-plus" @click="addDetail"
                  >新增
                </el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productpackingconfig_delete && this.packingConfigId" @click="detailHandleDelete"
                  >删 除
                </el-button>
                <span v-if="this.packingConfigId" style="margin-left: 10px">名称：{{ this.packingName }}</span>
              </template>
              <template slot-scope="scope" slot="menu">
                <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.productpackingconfig_edit" @click.stop="opendetailRow(scope.row, 'edit')"
                  >编辑</el-button
                >
                <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.productpackingconfig_delete" @click.stop="detailRowDel(scope.row, scope.index, done)"
                  >删除
                </el-button>
                <el-button type="text" icon="el-icon-circle-plus-outline" size="small" v-if="permission.productpackingconfig_addSubItem" @click.stop="handleAdd(scope.row)"
                  >新增子项
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-document-copy"
                  size="small"
                  v-if="permission.productpackingconfig_copySubItem"
                  @click.stop="opendetailRow(scope.row, 'copy')"
                  >复制
                </el-button>
              </template>
              <!-- <template slot-scope="{ row }" slot="isOutPack">
            <el-tag>{{ row.isOutPack === false ? '否' : '是' }}</el-tag>
          </template> -->
              <template slot-scope="{ row }" slot="isWeight">
                <el-tag :class="row.isWeight ? 'successTag' : 'dangerTag'">{{ row.isWeight === false ? '否' : '是' }}</el-tag>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" top="5vh" @close="closeDialog">
      <el-tabs type="border-card" v-if="showDialog" v-model="tabsIndex">
        <el-tab-pane label="基础数据" name="1">
          <avue-form ref="basicDataForm" v-model="detailForm" :option="basicDataOption"></avue-form>
        </el-tab-pane>
        <el-tab-pane label="包装信息" name="2">
          <avue-form ref="packInfoForm" v-model="packInfoForm" :option="packInfoOption"></avue-form>
          <!-- <avue-crud
            :option="packInfoOption"
            :data="packInfoData"
            v-model="packInfoForm"
            ref="packInfoCrud"
            @row-update="packInfoRowUpdate"
            @row-save="packInfoRowSave"
            @row-del="packInfoDetailRowDel"
          >
          </avue-crud> -->
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="detailSave"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="detailSave"> <i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getPackingconfigDetail,
  addPackingconfigDetail,
  removePackingconfigDetail,
  getDetailPackingconfigDetail
} from '@/api/admin/productpackingconfig';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    var validMaxWeight2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入最大重量(装箱时)'));
      }
      if (value < this.detailForm.minWeight2) {
        callback(new Error('最大重量不能小于最小重量'));
      } else {
        callback();
      }
    };
    var validMinWeight2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入最小重量(装箱时)'));
      }
      if (value > this.detailForm.maxWeight2) {
        callback(new Error('最大重量不能小于最小重量'));
      } else {
        callback();
      }
    };
    var validMaxWeight = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入最大重量(封箱时)'));
      }
      if (value < this.detailForm.minWeight) {
        callback(new Error('最大重量不能小于最小重量'));
      } else {
        callback();
      }
    };
    var validMinWeight = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入最小重量(封箱时)'));
      }
      if (value > this.detailForm.maxWeight) {
        callback(new Error('最大重量不能小于最小重量'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      isSubitem: false, //是否新增子项
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      selectionList: [],
      packingQuantity: '',
      option: {
        height: 'calc(100vh - 450px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 7,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 130,
        menuWidth: 150,
        highlightCurrentRow: true, // 选中高亮
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品编码',
            prop: 'partNo',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartCommonModal();
            }
          },
          {
            label: '产品名称',
            prop: 'partMasterName',
            disabled: true
          },
          {
            label: '产品规格',
            prop: 'partModel',
            disabled: true
          },
          {
            label: '线上打条码',
            prop: 'isOnlinePrint',
            type: 'switch',
            value: false,
            align: 'center',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3 //定义多行文本最小行数
          }
        ]
      },
      data: [],
      packingConfigId: '', //选中包装配置id
      packingName: '', //包装配置名称
      tableOption: {}, //公用模态框配置信息
      detailLoading: false,
      dialogTitle: '新增',
      showDialog: false,
      detailData: [], //包装详情数据
      detailOption: {
        //包装详情列表内容配置
        height: 'calc(100vh - 293px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        lazy: true, // 懒加载
        tree: true,
        menuWidth: 260,
        column: [
          {
            label: '编码',
            prop: 'code',
            width: 150
          },
          {
            label: '名称',
            prop: 'name'
          },
          {
            label: '包装数量',
            prop: 'packingQuantity'
          },
          // {
          //   label: '外包箱（最外层包装）',
          //   prop: 'isOutPack',
          //   align: 'center'
          // },
          {
            label: '称重',
            prop: 'isWeight',
            align: 'center'
          },
          {
            label: '包装最大重量',
            prop: 'maxWeight'
          },
          {
            label: '包装最小重量',
            prop: 'minWeight'
          }
        ]
      },
      tabsIndex: '1',
      basicDataOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 135,
        column: [
          {
            label: '编码',
            prop: 'code',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '包装数量',
            prop: 'packingQuantity',
            type: 'number',
            span: 8,
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入包装数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '称重',
            prop: 'isWeight',
            type: 'switch',
            span: 24,
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            control: (val, form) => {
              if (form.isWeight) {
                return {
                  sealingOpportunity: {
                    display: true
                  }
                };
              } else {
                return {
                  sealingOpportunity: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: '最大重量(装箱时)',
            prop: 'maxWeight2',
            type: 'number',
            span: 8,
            minRows: 0,
            display: false,
            rules: [{ validator: validMaxWeight2, trigger: 'blur' }]
          },
          {
            label: '最小重量(装箱时)',
            prop: 'minWeight2',
            type: 'number',
            span: 8,
            minRows: 0,
            display: false,
            rules: [{ validator: validMinWeight2, trigger: 'blur' }]
          },
          {
            label: '',
            prop: 'sealingOpportunity',
            type: 'checkbox',
            span: 8,
            disabled: this.readOnlyPage,
            dicData: [
              {
                label: '装箱时',
                value: 'BOXING'
              },
              {
                label: '封箱时',
                value: 'SEALING'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择装箱时/封箱时',
                trigger: 'submit'
              }
            ],
            change: (val) => {
              const maxWeight2 = this.findObject(this.basicDataOption.column, 'maxWeight2');
              const minWeight2 = this.findObject(this.basicDataOption.column, 'minWeight2');
              const maxWeight = this.findObject(this.basicDataOption.column, 'maxWeight');
              const minWeight = this.findObject(this.basicDataOption.column, 'minWeight');
              const isWeight = this.findObject(this.basicDataOption.column, 'isWeight');
              if (this._indexOf(val.value, 'BOXING') != -1) {
                isWeight.span = 8;
                maxWeight2.display = true;
                minWeight2.display = true;
              } else {
                maxWeight2.display = false;
                minWeight2.display = false;
                isWeight.span = 24;
              }
              if (this._indexOf(val.value, 'SEALING') != -1) {
                maxWeight.display = true;
                minWeight.display = true;
              } else {
                maxWeight.display = false;
                minWeight.display = false;
              }
            }
          },
          {
            label: '最大重量(封箱时)',
            prop: 'maxWeight',
            type: 'number',
            span: 8,
            minRows: 0,
            display: false,
            rules: [{ validator: validMaxWeight, trigger: 'blur' }]
          },
          {
            label: '最小重量(封箱时)',
            prop: 'minWeight',
            type: 'number',
            span: 8,
            minRows: 0,
            display: false,
            rules: [{ validator: validMinWeight, trigger: 'blur' }]
          },
          {
            label: '层级',
            prop: 'level',
            type: 'number',
            display: false,
            hide: true
          },
          {
            label: '父级ID',
            prop: 'parentId',
            hide: true,
            display: false
          },
          {
            label: '客户ID',
            prop: 'tenantId',
            hide: true,
            display: false
          },
          {
            label: '产品包装配置ID',
            prop: 'productPackingConfigId',
            hide: true,
            display: false
          }
        ]
      },
      packInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 280,
        column: [
          {
            label: '序列号名称',
            prop: 'sequenceDefinitionName',
            type: 'search',
            span: 18,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择序列号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openSequenceDefinitionCommonModal();
            }
          },
          {
            label: '打印标签名称',
            prop: 'labelTemplateName',
            type: 'search',
            span: 18,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印标签名称',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateCommonModal();
            }
          }
        ]
      },
      detailForm: {},
      packInfoForm: {},
      packInfoData: [],
      modalName: '', //公用模态框名称
      selectionDetailList: [],
      parentId: '',
      isShowDetailTable: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.productpackingconfig_add, false),
        viewBtn: this.vaildData(this.permission.productpackingconfig_view, false),
        delBtn: this.vaildData(this.permission.productpackingconfig_delete, false),
        editBtn: this.vaildData(this.permission.productpackingconfig_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    detailIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      this.isShowDetailTable = true;
    });
  },
  watch: {
    'detailForm.isWeight'(val) {
      if (!val) {
        this.detailForm.sealingOpportunity = [];
        const maxWeight2 = this.findObject(this.basicDataOption.column, 'maxWeight2');
        const minWeight2 = this.findObject(this.basicDataOption.column, 'minWeight2');
        const maxWeight = this.findObject(this.basicDataOption.column, 'maxWeight');
        const minWeight = this.findObject(this.basicDataOption.column, 'minWeight');
        const isWeight = this.findObject(this.basicDataOption.column, 'isWeight');
        maxWeight2.display = false;
        minWeight2.display = false;
        this.detailForm.maxWeight2 = undefined;
        this.detailForm.minWeight2 = undefined;
        isWeight.span = 24;
        maxWeight.display = false;
        minWeight.display = false;
        this.detailForm.maxWeight = undefined;
        this.detailForm.minWeight = undefined;
      }
    }
  },
  methods: {
    rowSave(row, done, loading) {
      let params = {
        isOnlinePrint: row.isOnlinePrint,
        code: row.code,
        name: row.name,
        partName: row.partName,
        partSpecifications: row.partSpecifications,
        remark: row.remark,
        partMasterId: row.partMasterId
      };
      add(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.extFields = null;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
      this.rowClick(list[len]);
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.detailOption.addBtn = false;
        this.detailData = [];
        this.selectionDetailClear();
      });
    },
    /**
     * 单击事件
     */
    rowClick(row) {
      this.packingConfigId = row.id;
      this.packingName = row.name;
      this.onDetailLoad();
    },
    /**
     * 打开物料选择模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'partModal') {
        this.form.partMasterId = rowData.id;
        this.form.partNo = rowData.partNo;
        this.form.partMasterName = rowData.name;
        this.form.partModel = rowData.partModel;
      } else if (this.modalName === 'serialNumberModal') {
        this.packInfoForm.sequenceDefinitionId = rowData.id;
        this.packInfoForm.sequenceDefinitionName = rowData.name;
        this.packInfoForm.sequenceNoFormat = rowData.sequenceNoFormat;
      } else if (this.modalName === 'labelTemplateModal') {
        this.packInfoForm.labelTemplateId = rowData.id;
        this.packInfoForm.labelTemplateName = rowData.fileName;
      }
    },
    /**
     * 打开新增模态框
     */
    addDetail() {
      // if (this.detailData.length > 0) {
      //   this.$message({
      //     type: 'warning',
      //     message: '已存在外层包装！'
      //   });
      //   return;
      // }
      this.showDialog = true;
      this.modalName = '新增';
    },
    /**
     * 打开编辑模态框
     */
    opendetailRow(row, type) {
      this.showDialog = true;
      this.dialogTitle = type === 'edit' ? '编辑' : '新增';
      getDetailPackingconfigDetail(row.id).then((res) => {
        let result = this._get(res, 'data.data', {});
        if (type === 'edit') {
          this.detailForm = result;
          this.detailForm.sealingOpportunity = [];
          if (result.weightPoint === 'SEALING') {
            this.detailForm.sealingOpportunity = ['SEALING'];
          } else if (result.weightPoint === 'BOXING') {
            this.detailForm.sealingOpportunity = ['BOXING'];
          } else if (result.weightPoint === 'BOTH') {
            this.detailForm.sealingOpportunity = ['BOXING', 'SEALING'];
          }
        }
        this.packInfoForm.sequenceDefinitionId = this._get(result, 'sequenceDefinitionId', '');
        this.packInfoForm.sequenceDefinitionName = this._get(result, 'sequenceDefinitionName', '');
        this.packInfoForm.labelTemplateId = this._get(result, 'labelTemplateId', '');
        this.packInfoForm.labelTemplateName = this._get(result, 'labelTemplateName', '');
      });
    },
    /**
     * 包装详情新增子项
     */
    handleAdd(row) {
      if (row.hasChildren) {
        this.$message({
          type: 'warning',
          message: '当前行已存在子项！'
        });
        return;
      }
      this.parentId = row.id;
      this.packingQuantity = row.packingQuantity;
      this.showDialog = true;
      this.isSubitem = true;
      this.dialogTitle = '新增';
    },

    /**
     * 保存包装配置详情
     */
    async detailSave() {
      this.detailForm.productPackingConfigId = this.packingConfigId;
      let validData1 = await new Promise((resolve, reject) => {
        this.$refs.basicDataForm.validate((valid, done) => {
          if (valid) {
            if (this.isSubitem) {
              if (this.detailForm.packingQuantity > this.packingQuantity) {
                this.$message({
                  type: 'warning',
                  message: '下一层包装数量不能大于上一层包装数量！'
                });
                this.tabsIndex = '1';
                done();
                return;
              }
              this.isSubitem = false;
            }
            resolve();
            done();
          } else {
            this.tabsIndex = '1';
          }
        });
      });
      let validData2 = new Promise((resolve, reject) => {
        this.$refs.packInfoForm.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '2';
          }
        });
      });
      Promise.all([validData1, validData2]).then(() => {
        this.detailForm.sequenceDefinitionId = this.packInfoForm.sequenceDefinitionId;
        this.detailForm.labelTemplateId = this.packInfoForm.labelTemplateId;
        if (this.detailForm.sealingOpportunity.length > 1) {
          this.detailForm['weightPoint'] = 'BOTH';
        } else if (this.detailForm.sealingOpportunity.length === 1) {
          this.detailForm['weightPoint'] = this.detailForm.sealingOpportunity[0];
          if (this.detailForm.sealingOpportunity[0] === 'SEALING') {
            this.detailForm.maxWeight2 = '';
            this.detailForm.minWeight2 = '';
          } else {
            this.detailForm.maxWeight = '';
            this.detailForm.minWeight = '';
          }
        } else {
          this.detailForm['weightPoint'] = '';
          this.detailForm.maxWeight = '';
          this.detailForm.minWeight = '';
          this.detailForm.maxWeight2 = '';
          this.detailForm.minWeight2 = '';
        }
        if (this.dialogTitle === '新增') {
          this.detailForm.parentId = this.parentId;
          addPackingconfigDetail(this.detailForm).then(
            () => {
              // this.refreshChange();
              this.onDetailLoad();
              this.$message({
                type: 'success',
                message: '新增成功!'
              });
              this.showDialog = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else if (this.dialogTitle === '编辑') {
          addPackingconfigDetail(this.detailForm).then(
            () => {
              this.onDetailLoad();
              this.$message({
                type: 'success',
                message: '编辑成功!'
              });
              this.showDialog = false;
            },
            (error) => {
              console.log(error);
            }
          );
        }
      });
    },
    closeDialog() {
      this.$refs.basicDataForm.resetFields();
      this.$refs.packInfoForm.resetFields();
      this.detailForm = {};
      this.packInfoForm = {};
      this.tabsIndex = '1';
    },
    detailRowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePackingconfigDetail(row.id);
        })
        .then((res) => {
          if (res.data.success) {
            this.onDetailLoad();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            done(row); //刷新树表格
          } else {
            this.$message({
              type: 'error',
              message: '操作失败!'
            });
          }
        });
    },
    /**
     * 查询包装配置详情
     */
    onDetailLoad() {
      this.detailLoading = true;
      getPackingconfigDetail(this.packingConfigId).then((res) => {
        const data = res.data.data;
        this.detailData = data;
        // this.$set(this.detailData ,)
        this.detailLoading = false;
        this.selectionDetailClear();
      });
    },
    detailRefreshChange() {
      this.onDetailLoad();
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      this.$refs.detailCrud.toggleSelection();
    },
    detailHandleDelete(scope) {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePackingconfigDetail(this.detailIds);
        })
        .then(() => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.detailCrud.toggleSelection();
        });
    },
    /**
     * 产品包装配置详情懒加载
     */
    treeLoad(tree, treeNode, resolve) {
      let productPackingConfigId = this.packingConfigId;
      let parentId = tree.id;
      getPackingconfigDetail(productPackingConfigId, parentId).then((res) => {
        resolve(res.data.data);
      });
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSequenceDefinitionCommonModal() {
      this.modalName = 'serialNumberModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择成品包装条码（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material&subType=finished_product_packaging',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '规则编码',
            prop: 'code',
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat',
            labelslot: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 打开标签模版选择模态框
     */
    openLabelTemplateCommonModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?type=material&subType=finished_product_packaging&status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            }
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },
    /**
     * 包装信息保存
     */
    packInfoRowSave(row, done) {
      this.packInfoData.push(row);
      done();
    },
    /**
     * 包装信息修改
     */
    packInfoRowUpdate(row, index, done) {
      this.$set(this.packInfoData, index, row);
      done();
    },
    /**
     * 包装信息删除
     */
    packInfoDetailRowDel(row, index) {
      this.packInfoData.splice(index, 1);
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
